package com.company.emallbackend.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.emallbackend.common.Result;
import com.company.emallbackend.entity.Comment;
import com.company.emallbackend.entity.Product;
import com.company.emallbackend.exception.CommonException;
import com.company.emallbackend.service.ICommentService;
import com.company.emallbackend.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Objects;

/**
* <p>
*  前端控制器
* </p>
*
* @author hanlijian
* @since 2023-01-12
*/
@RestController
@RequestMapping("/product")
@Api(tags = "商品管理")
public class ProductController {

    @Resource
    private IProductService productService;
    @Resource
    private ICommentService commentService;
    
    @PostMapping
    @ApiOperation("新增商品")
    public Result save(@RequestBody Product product) {
        productService.save(product);
        return Result.success();
    }
    
    @PutMapping
    @ApiOperation("修改商品信息")
    public Result update(@RequestBody Product product) {
        productService.updateById(product);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除商品")
    public Result delete(@PathVariable Integer id) {
        productService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    @ApiOperation("批量删除商品")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        productService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping("findAll")
    @ApiOperation("查询所有商品")
    public Result findAll() {
        List<Product> productList = productService.list();
        //根据商品id查询商品评论列表
        List<Product> products=findCommentListByProuductList(productList);
        return Result.success(products);
    }

    private List<Product> findCommentListByProuductList(List<Product> productList) {
        for (Product product : productList) {
            Integer productId = product.getId();
            List<Comment> commentList = commentService.list(new QueryWrapper<Comment>().eq("product_id", productId));
            product.setCommentList(commentList);
        }
        return productList;
    }

    @GetMapping("getById/{id}")
    @ApiOperation("根据id查询商品")
    public Result findOne(@PathVariable Integer id) {
        if(Objects.isNull(id)){
            throw new CommonException(201,"请检查您要查询的商品");
        }
        Product product = productService.getById(id);
        if(Objects.isNull(product)){
            throw new CommonException(201,"系统繁忙,稍后再试");
        }
        //根据productId查询Comment表
        List<Comment> commentList = commentService.list(new QueryWrapper<Comment>().eq("product_id", id));
        product.setCommentList(commentList);
        return Result.success(product);
    }

    @GetMapping("/page")
    @ApiOperation("分页查询商品")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<Product> queryWrapper = new QueryWrapper<Product>().orderByDesc("id");
        queryWrapper.like(!"".equals(name), "name", name);
        Page<Product> productList = productService.page(new Page<>(pageNum, pageSize), queryWrapper);
        return Result.success(productList);
    }

    /**
    * 导出接口
    */
    @GetMapping("/export")
    @ApiOperation("导出商品信息")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Product> list = productService.list();
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        // 一次性写出list内的对象到excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("Product信息表", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    /**
    * excel 导入
    * @param file
    * @throws Exception
    */
    @PostMapping("/import")
    @ApiOperation("导入商品信息")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        // 通过 javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟javabean的属性要对应起来
        List<Product> list = reader.readAll(Product.class);

        productService.saveBatch(list);
        return Result.success();
    }

    /**
     * 上传商品图片
     * @param file
     * @return
     */
    @PostMapping("upload")
    @ApiOperation("上传商品图片")
    public Result upload(MultipartFile file){
        String uploadUrl=productService.upload(file);
        return Result.success(uploadUrl);
    }

}
